// utils/onenet-api.js
const onenetConfig = require('./onenet-config.js')

class OneNETAPI {
  constructor() {
    this.baseUrl = onenetConfig.api.baseUrl
    this.apiKey = onenetConfig.api.apiKey
  }

  // 获取设备详情
  async getDeviceInfo() {
    return this.request({
      url: `/devices/${onenetConfig.product.deviceName}`,
      method: 'GET'
    })
  }

  // 获取设备数据流
  async getDataStreams() {
    return this.request({
      url: `/devices/${onenetConfig.product.deviceName}/datastreams`,
      method: 'GET'
    })
  }

  // 获取历史数据
  async getHistoryData(datastreamId, start, end, limit = 100) {
    return this.request({
      url: `/devices/${onenetConfig.product.deviceName}/datapoints`,
      method: 'GET',
      data: {
        datastream_id: datastreamId,
        start: start,
        end: end,
        limit: limit
      }
    })
  }

  // 发送命令到设备
  async sendCommand(cmd) {
    return this.request({
      url: `/cmds?device_id=${onenetConfig.product.deviceName}`,
      method: 'POST',
      data: cmd
    })
  }

  // 通用请求方法
  async request(options) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: this.baseUrl + options.url,
        method: options.method || 'GET',
        data: options.data,
        header: {
          'api-key': this.apiKey,
          'Content-Type': 'application/json'
        },
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res.data)
          } else {
            reject(new Error(`HTTP ${res.statusCode}: ${res.data}`))
          }
        },
        fail: (error) => {
          reject(error)
        }
      })
    })
  }
}

module.exports = new OneNETAPI()